package com.foryou.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.foryou.wechat.common.Constants;
import com.foryou.wechat.entity.SubjectEntity;
import com.foryou.wechat.mapper.SubjectMapper;
import com.foryou.wechat.model.dto.SubjectDTO;
import com.foryou.wechat.model.vo.FormSubjectVo;
import com.foryou.wechat.service.SubjectService;
import com.foryou.wechat.utils.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Lee.
 */
@Service
public class SubjectServiceImpl implements SubjectService {

    @Autowired
    private SubjectMapper subjectMapper;

    @Override
    public int addSubject(String name) {

        if (StringUtils.isBlank(name)) {
            return 0;
        }

        SubjectEntity subjectEntity = subjectMapper.selectOne(
                new QueryWrapper<SubjectEntity>().eq("name", name));

        if (subjectEntity != null) {
            throw new RuntimeException(Constants.DATA_EXIST);
        }
        return subjectMapper.insert(new SubjectEntity(name));
    }

    @Override
    public int updateSubject(SubjectDTO subjectDTO) {

        SubjectEntity subjectEntity = subjectMapper.selectOne(
                new QueryWrapper<SubjectEntity>().eq("name", subjectDTO.getName()));

        if (null!=subjectEntity && !subjectDTO.getSubjectId().equals(subjectEntity.getId())) {
            throw new RuntimeException(Constants.DATA_EXIST);
        }

        return subjectMapper.updateById(new SubjectEntity(
                subjectDTO.getSubjectId(),
                subjectDTO.getName(),
                subjectDTO.isEnabled()?0:1
        ));
    }

    @Override
    public Response querySelectList(Map<String,Object> params) {
        List<SubjectEntity> selectList = subjectMapper.selectByMap(params);
        return Response.success(selectList);
    }

    @Override
    public Response getSubjectDetail(Long subjectId) {
        SubjectEntity subjectEntity = subjectMapper.selectById(subjectId);
        return Response.success(subjectEntity);
    }

    @Override
    public Response querySelectList() {
        Map<String, Object> params = new HashMap<>();
        params.put("status", 1);
        List<SubjectEntity> selectList = subjectMapper.selectByMap(params);
        List<FormSubjectVo> formList = new ArrayList<>();
        selectList.forEach(e->{
            formList.add(new FormSubjectVo(e.getId(), e.getName()));
        });
        return Response.success(formList);
    }
}
